package utils

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

// 读取配置文件
func InitConfig() {
	viper.AddConfigPath("config")
	viper.SetConfigName("application")
	viper.SetConfigType("yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}

	fmt.Printf("init Config success, %+v\n", viper.Get("mysql"))
	fmt.Printf("init Config success, %+v\n", viper.Get("redis"))
}

// 打开mysql
func InitMySql() *gorm.DB {

	// 打印日志
	logConfig := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second, // 慢sql日志
			LogLevel:      logger.Info, // 日志级别
			Colorful:      true,        // 开启颜色
		},
	)

	db, err := gorm.Open(mysql.Open(viper.GetString("mysql.env")), &gorm.Config{Logger: logConfig})

	if err != nil {
		panic(err)
	}

	// 根据 结构体自动创建表
	//fmt.Println("create table user_basic")
	//db.AutoMigrate(model.UserBasic{})
	return db
}

func InitRedis() {
	redisConfig := redis.NewClient(&redis.Options{
		Addr:         fmt.Sprintf("%s:%d", viper.GetString("redis.host"), viper.GetInt("redis.port")),
		Password:     viper.GetString("redis.password"),
		DB:           viper.GetInt("redis.db"),
		PoolSize:     viper.GetInt("redis.poolSize"),
		MinIdleConns: viper.GetInt("redis.minIdleConn"),
	})

	pong, err := redisConfig.Ping().Result()
	if err != nil {
		panic(err)
	}
	fmt.Println(pong)
}
